package com.app.activitys;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.ByteArrayBuffer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.MediaColumns;
import android.content.ContentValues;
import android.database.Cursor;


import com.app.activitys.adapters.SelectedAdapter;
import com.app.entidades.Musicas;
import com.app.player.InterfaceMp3;
import com.app.player.ServicoPlayer;
import com.app.player.ServicoPlayer.ConexaoInterfaceMp3;
import com.example.applucianokikao.R;

public class Faixas extends Activity implements OnItemClickListener{

	private ArrayList<Musicas> listaMusicas;
	private List<String> nomeFaixas;
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnAvancar;
	private ImageButton btnRetornar;
	private ImageButton btnDown;
	private SeekBar songProgressBar;
	private TextView tituloMusica;
	private ListView lista;
	private SelectedAdapter selectedAdapter;
	private InterfaceMp3 interfaceMp3;
	private boolean progress=false;
	private Handler handler = new Handler();
	private boolean tocou=false;
	private Context contexto;
	private Dialog dialog;
	private int avancar = 5000;
	private int voltar = 5000; 
	private Intent intentService;
	
	private ServiceConnection conexao = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			interfaceMp3 = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			ConexaoInterfaceMp3 conexao = (ConexaoInterfaceMp3) service;
			interfaceMp3 = conexao.getService();
		}
	};
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.layout_player);
		
		dialog = criarDialog();
		contexto = this;
		intentService = new Intent(Faixas.this, ServicoPlayer.class);
		startService(intentService);
		bindService(intentService, conexao, Context.BIND_AUTO_CREATE);	
		
		Bundle extras = getIntent().getExtras();
		Bundle valor = extras.getBundle("mus");
		listaMusicas = (ArrayList<Musicas>) valor.getSerializable("musicas");
		nomeFaixas = retornaNomes(listaMusicas);
		
		selectedAdapter = new SelectedAdapter(this,0,nomeFaixas);
		selectedAdapter.setNotifyOnChange(true);
		lista = (ListView) findViewById(R.id.listaComposicoes);
		lista.setAdapter(selectedAdapter);
		lista.setOnItemClickListener((OnItemClickListener)this);
		lista.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnAvancar = (ImageButton) findViewById(R.id.btnForward);
		btnRetornar = (ImageButton) findViewById(R.id.btnBackward);
		btnDown = (ImageButton) findViewById(R.id.btnDownload);
		tituloMusica = (TextView) findViewById(R.id.titulo_musica);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		
		btnDown.setEnabled(false);
		
		Log.i("ccarvalho", "Bandas: " + nomeFaixas);
		
	btnPlay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!tocou){
					tocou = true;
					btnPlay.setImageResource(R.drawable.btn_pause);
					dialog.show();
					tocarMusica(listaMusicas.get(0));
					btnDown.setEnabled(true);
				}else{
					if(interfaceMp3.isTocando()){
						interfaceMp3.pausar();
						btnPlay.setImageResource(R.drawable.btn_play);
					}else{
						interfaceMp3.tocar();
						btnPlay.setImageResource(R.drawable.btn_pause);
					}
				}
			}
		});
		
		btnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!tocou){
					tocou = true;
					setLinha(0);
					btnPlay.setImageResource(R.drawable.btn_pause);
					dialog.show();
					tocarMusica(listaMusicas.get(0));
					btnDown.setEnabled(true);
				}else{
					progress = false;
					dialog.show();
					interfaceMp3.parar();
					Musicas musica = passarMusica();
					tocarMusica(musica);
				}
			}
		});	
	
		btnPrevious.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!tocou){
					tocou = true;
					setLinha(0);
					btnPlay.setImageResource(R.drawable.btn_pause);
					dialog.show();
					tocarMusica(listaMusicas.get(0));
					btnDown.setEnabled(true);
				}else{
					progress = false;
					dialog.show();
					interfaceMp3.parar();
					Musicas musica = voltarMusica();
					tocarMusica(musica);
				}
			}
		});
		
		btnAvancar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(tocou){
					int posicaoCorrente = interfaceMp3.getPosicaoMusica();
					
					if((posicaoCorrente+avancar) <=interfaceMp3.getDuracao()){
						interfaceMp3.setPosicaoMusica(posicaoCorrente+avancar);
					}else{
						interfaceMp3.setPosicaoMusica(interfaceMp3.getDuracao());
					}
				}	
			}
		});
		
		btnRetornar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tocou){
					int posicaoCorrente = interfaceMp3.getPosicaoMusica();
					
					if((posicaoCorrente - voltar) >=0){
						interfaceMp3.setPosicaoMusica(posicaoCorrente - voltar);
					}else{
						interfaceMp3.setPosicaoMusica(0);
					}
				}
			}
		});
		
		btnDown.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int posi = retornaPosicaoMusicaTocando(interfaceMp3.getMusicaCorrente());
				final Musicas musica = retornaMusica(posi);
				
				AsyncTask<Void, Void,Void> task = new AsyncTask<Void,Void,Void>(){

					@Override
					protected void onPreExecute(){
						Toast.makeText(contexto, "O download da musica "+musica.getTitulo()+" iniciou.",Toast.LENGTH_SHORT).show();
					    System.out.println("baixando");
					}
					
					@Override
					protected Void doInBackground(Void... params) {
				        try {
				        	URL aURL = new URL(musica.getArquivo());
						    URLConnection conn = aURL.openConnection();
						    conn.connect();
						        
						    InputStream is = conn.getInputStream();
						    final BufferedInputStream bis = new BufferedInputStream(is);
						    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/Musicas/"+musica.getTitulo());
						    FileOutputStream fos = new FileOutputStream(file);
						    fos.write(getBytes(bis));
						    fos.flush();
						    fos.close();
						    
						    ContentValues values = new ContentValues();
						    values.put(Media.DATA, file.getAbsolutePath());
						    values.put(Media.DISPLAY_NAME, "Musica do Kikão");
						    values.put(Media.DURATION, interfaceMp3.getDuracao());
						    values.put(Media.TITLE, musica.getTitulo());
						    values.put(Media.MIME_TYPE, "audio/mp3");
						    values.put(Media.ALBUM, "Luciano Kikão");
						    values.put(Media.ARTIST, "Luciano Kikão - Compositor das Multidões");
						    values.put(Media.IS_ALARM, 0);
						    values.put(Media.IS_NOTIFICATION, 0);
						    values.put(Media.IS_PODCAST, 0);
						    values.put(Media.IS_RINGTONE, 0);
						    values.put(Media.IS_MUSIC, 1);
						    
						    Uri uri = getContentResolver().insert(Media.getContentUriForPath(file.getAbsolutePath()), values);
						    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
						    bis.close();
						    is.close();
					
						    
					   } catch (IOException e) {
						      Log.e("ImagemButton", "Error getting bitmap", e);
					   }
				        return null;
					}
					
					@Override
			        protected void onPostExecute(Void result) {
						Toast.makeText(contexto, "O download da musica "+musica.getTitulo()+" foi concluido.",Toast.LENGTH_SHORT).show();
					    System.out.println("Terminou");
					}
				};
				task.execute();		
			}
		});
		
		
	}
	
	@Override
	protected void onDestroy() {
		progress = false;
		interfaceMp3.parar();
		unbindService(conexao);
		stopService(intentService);
		super.onDestroy();
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		setLinha(arg2);
		
		if(tocou){
			progress = false;
			dialog.show();
			interfaceMp3.parar();
			tocarMusica(listaMusicas.get(arg2));
			if(!interfaceMp3.isTocando()){
				btnPlay.setImageResource(R.drawable.btn_pause);
			}
		}else{
			tocou = true;
			dialog.show();
			btnPlay.setImageResource(R.drawable.btn_pause);
			tocarMusica(listaMusicas.get(arg2));
			btnDown.setEnabled(true);
		}
		
	}

	public List<String> retornaNomes(ArrayList<Musicas> music) {
		List<String> nomes = new ArrayList<String>();
		for (Musicas b : music) {
			nomes.add(b.getTitulo());
		}
		return nomes;
	}

	public Musicas retornaMusica(int posicao){
		if(posicao > listaMusicas.size()-1){
			return listaMusicas.get(0);
		}else{
			return listaMusicas.get(posicao);
		}
	}
	public void startProgressBar(){
			
			AsyncTask<Void, Void,Boolean> task = new AsyncTask<Void,Void,Boolean>(){
				
				@Override
				protected void onPreExecute(){
					System.out.println("pre execute");
					progress = true;
					songProgressBar.setMax(interfaceMp3.getDuracao());
				}
				
				@Override
				protected Boolean doInBackground(Void... arg0) {
					System.out.println("background");
					
					while(!interfaceMp3.getTerminou() && progress){
	//					handler.post(new Runnable() {
	//							@Override
	//							public void run() {
									songProgressBar.setProgress(interfaceMp3.getPosicaoMusica());
									//publishProgress();
						//		}
						//});
					}
					System.out.println("saiu background");
					return progress;
				}
	
				@Override
		        protected void onPostExecute(Boolean result) {
					System.out.println("pos execute");
					if(result){
						System.out.println("entrou");
						dialog.show();
						Musicas musica = passarMusica();
						interfaceMp3.parar();
						tocarMusica(musica);			
					}
				};
				
				
			};
			task.execute();
	
	}

	
	public int retornaPosicaoMusicaTocando(String arquivo){
		int posicao=-1;
		for(Musicas m: listaMusicas){
			if(m.getArquivo()==arquivo){
				posicao = listaMusicas.indexOf(m);
			}
		}
		return posicao; 
	}
	
	public Musicas passarMusica(){
		int posi = retornaPosicaoMusicaTocando(interfaceMp3.getMusicaCorrente());
		if(posi==listaMusicas.size()-1){
			posi=0;
		}else{
			posi++;
		}
		setLinha(posi);
		Musicas mu = retornaMusica(posi);
		return mu;
	}
	
	public Musicas voltarMusica(){
		int posi = retornaPosicaoMusicaTocando(interfaceMp3.getMusicaCorrente());
		if(posi==0){
			posi= listaMusicas.size()-1;
		}else{
			posi--;
		}
		setLinha(posi);
		Musicas mu = retornaMusica(posi);
		return mu;
	}
	
	public void tocarMusica(final Musicas musica){
		new Thread(new Runnable() {	
			@Override
			public void run() {
				handler.post(new Runnable() {
					@Override
					public void run() {
						tituloMusica.setText(musica.getTitulo());	
					}
				});
				interfaceMp3.iniciar(musica.getArquivo());
				startProgressBar();
				dialog.dismiss();
				
			}
		}).start();
	}
	
	 
	public void setLinha(final int posicao){
			new Thread(new Runnable() {	
				@Override
				public void run() {
					handler.post(new Runnable() {
						@Override
						public void run() {
							selectedAdapter.setSelectedPosition(posicao);
						}
					});
				}
			}).start();
	}
	
	public Dialog criarDialog(){
		Dialog di = new Dialog(this,R.style.Theme_Dialog_Translucent);
		di.setTitle("Carregando Música");
        di.setCancelable(false);
        di.setContentView(R.layout.theme);
		return di;
	}
	
	public byte[] getBytes(BufferedInputStream bis){
		ByteArrayBuffer baf = new ByteArrayBuffer(50);

		int count = 0;

		try {
			while((count = bis.read()) != -1){
				baf.append((byte) count);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return baf.toByteArray();
	}
	
}
